package com.example.exam.controller;

import com.alibaba.excel.EasyExcel;
import com.example.exam.constant.DocumentConstant;
import com.example.exam.pojo.*;
import com.example.exam.service.AchievementService;
import com.example.exam.service.QuestionBankService;
import com.example.exam.service.TestPaperService;
import com.example.exam.service.UserService;
import com.example.exam.utils.JsonUtil;
import com.example.exam.utils.R;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author
 * @date 2023/05/23
 *
 * 成绩管理
 */
@RequestMapping("/management")
@RestController
@RequiredArgsConstructor
public class GradeController {

    private final UserService userService;
    private final AchievementService achievementService;
    private final QuestionBankService questionBankService;
    private final TestPaperService testPaperService;

    /**
     * 参考学生列表
     */
    @GetMapping("/referenceUserList")
    public Object referenceUserList() {
        List<User> list = userService.searchGrade();
        return R.ok(list);
    }

    /**
     * 查看题目
     */
    @GetMapping("/getQuestion")
    public Object getQuestion() {
        List<QuestionBank> list = questionBankService.searchQuestionBankList();
        return R.ok(list);
    }

    /**
     * 查看答案
     */
    @GetMapping("/preview/{sid}")
    public Object preview(@PathVariable String sid) {
        List<TestPaper> testPapers = testPaperService.searchAllBySid(sid);
        List<Achievement> achievements = achievementService.searchAllBySid(sid);
        //根据题号排序
        Collections.sort(testPapers);
        Collections.sort(achievements);
        List<TestPaperVo> testPaperVos = new ArrayList<>();
        int n = 0;
        for(TestPaper testPaper : testPapers) {
            if(n < achievements.size() && testPaper.getTid() == achievements.get(n).getTid()) {
                testPaperVos.add(new TestPaperVo(testPaper, achievements.get(n).getGrade()));
                n++;
            }else {
                testPaperVos.add(new TestPaperVo(testPaper));
            }
        }
        return R.ok(testPaperVos);
    }

    /**
     * 录入成绩
     */
    @PostMapping("/inputAchievement")
    public Object inputAchievement(@RequestBody Achievement achievement, HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        String[] strs = new String(Base64.getDecoder().decode(token.getBytes())).split(":");
        achievement.setRater(strs[0]);
        Achievement achievement1 = achievementService.searchAllBySidAndTid(achievement);
        if(achievement1 != null) {
            achievementService.updateAchievementBySidAndTid(achievement);
        }else {
            achievementService.insert(achievement);
        }
        return R.ok();
    }

    /**
     * 确认成绩
     */
    @PostMapping("/submitAchievement")
    public Object submitAchievement(@RequestParam String sid) {
        int achievement = achievementService.searchAchievementBySid(sid);
        User user = new User();
        user.setSid(sid);
        user.setAchievement(achievement);
        userService.updateAchievement(user);
        return R.ok();
    }

    /**
     * 查看成绩表
     */
    @GetMapping("/ranking")
    public Object ranking() {
        List<User> userList = userService.searchAchievementList();
        return R.ok(userList);
    }

    /**
     * 导出成绩表(excel)
     *
     * .excludeColumnFiledNames(Set):设置要过滤掉的字段
     */
    @GetMapping("/exportGrade")
    public void batchDerive(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //设置字符集
            response.setCharacterEncoding("utf-8");
            //解决中文名称乱码问题
            String fileName = URLEncoder.encode("成绩", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + DocumentConstant.SUFFIX_XLSX);
            //查询成绩列表
            List<User> userList = userService.searchAchievementList();
            //这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), User.class).autoCloseStream(Boolean.FALSE)
                    .sheet("模板").doWrite(userList);
        } catch (IOException e) {
            //重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(3);
            map.put("status", "failure");
            map.put("message", "下载文件失败:" + e.getMessage());
            response.getWriter().println(JsonUtil.toString(map));
        }
    }
}
